<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-button type="primary" @click="handleAddNew">+ 添加</el-button>
        </el-form-item>
        <el-form-item label="组织结构">
          <el-input v-model="searchForm.organization" placeholder="请输入组织结构" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="searchForm.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="searchForm.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-box">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="interventionTime" label="干预时间" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="organization" label="组织结构" />
        <el-table-column prop="leader" label="负责人" />
        <el-table-column prop="lastModified" label="最后修改日期" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleAdd(scope.row)">添加</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="添加干预记录">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" :disabled="isNameDisabled" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" />
        </el-form-item>
        <el-form-item label="干预内容" prop="content">
          <el-input v-model="form.content" type="textarea" />
        </el-form-item>
        <el-form-item label="预警级别" prop="warningLevel">
          <el-radio-group v-model="form.warningLevel">
            <el-radio label="高度预警" />
            <el-radio label="中度预警" />
            <el-radio label="轻度预警" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="干预级别" prop="interventionLevel">
          <el-radio-group v-model="form.interventionLevel">
            <el-radio label="高关怀" />
            <el-radio label="危机干预" />
            <el-radio label="常规辅导" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否结案">
          <el-switch v-model="form.isClosed" />
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload
            action="#"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
          >
            <div style="display: flex; align-items: center;">
              <el-button type="primary">点击上传</el-button>
              <el-button type="text" @click.stop="handleDownloadTemplate" style="margin-left: 10px;">下载模板</el-button>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.xls, .xlsx, .doc, .docx, .ppt, .pptx, .zip，且不超过2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="干预时间" prop="interventionTime">
          <el-date-picker
            v-model="form.interventionTime"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleCreate">立即创建</el-button>
          <el-button @click="handleResetForm">重置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';

const searchForm = ref({
  organization: '',
  name: '',
  account: '',
  leader: '',
});

const allTableData = ref([]);
const tableData = ref([]);

const dialogVisible = ref(false);
const isNameDisabled = ref(false);
const formRef = ref(null);

const form = ref({
  name: '',
  leader: '',
  content: '',
  warningLevel: '',
  interventionLevel: '',
  isClosed: false,
  interventionTime: '',
});

const rules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  content: [{ required: true, message: '请输入干预内容', trigger: 'blur' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  interventionLevel: [{ required: true, message: '请选择干预级别', trigger: 'change' }],
  interventionTime: [{ required: true, message: '请选择干预时间', trigger: 'change' }],
});

const handleDownloadTemplate = () => {
  const link = document.createElement('a');
  link.href = '/心理干预记录 - 模版.docx';
  link.download = '心理干预记录 - 模版.docx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = (d.getMonth() + 1).toString().padStart(2, '0');
  const day = d.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const saveData = () => {
  sessionStorage.setItem('warningInterventionRecords', JSON.stringify(allTableData.value));
};

onMounted(() => {
  const storedData = sessionStorage.getItem('warningInterventionRecords');
  if (storedData) {
    allTableData.value = JSON.parse(storedData);
  } else {
    // Mock data
    allTableData.value = [
      { id: 1, interventionTime: '2023-10-01', name: '张三', account: 'zhangsan', organization: '学院A', leader: '李四', lastModified: '2023-10-01' },
      { id: 2, interventionTime: '2023-10-02', name: '李四', account: 'lisi', organization: '学院B', leader: '王五', lastModified: '2023-10-02' },
      { id: 3, interventionTime: '2023-10-03', name: '王五', account: 'wangwu', organization: '学院A', leader: '李四', lastModified: '2023-10-03' },
    ];
    saveData();
  }
  tableData.value = allTableData.value;
});

const handleSearch = () => {
  tableData.value = allTableData.value.filter(item => {
    return (
      (!searchForm.value.organization || item.organization.includes(searchForm.value.organization)) &&
      (!searchForm.value.name || item.name.includes(searchForm.value.name)) &&
      (!searchForm.value.account || item.account.includes(searchForm.value.account)) &&
      (!searchForm.value.leader || item.leader.includes(searchForm.value.leader))
    );
  });
};

const handleReset = () => {
  searchForm.value = {
    organization: '',
    name: '',
    account: '',
    leader: '',
  };
  tableData.value = allTableData.value;
};

const handleAddNew = () => {
  handleResetForm();
  isNameDisabled.value = false;
  dialogVisible.value = true;
};

const handleAdd = (row) => {
  handleResetForm();
  form.value.name = row.name;
  isNameDisabled.value = true;
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  allTableData.value = allTableData.value.filter(item => item.id !== row.id);
  saveData();
  handleSearch();
};

const handleCreate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const newRecord = {
        ...form.value,
        id: Date.now(),
        account: 'newuser', // This should be dynamic in a real app
        organization: '学院C', // This should be dynamic in a real app
        lastModified: new Date().toISOString().split('T')[0],
        interventionTime: formatDate(form.value.interventionTime),
      };
      allTableData.value.push(newRecord);
      saveData();
      handleSearch();
      dialogVisible.value = false;
    } else {
      ElMessage.error('请填写所有必填项');
      return false;
    }
  });
};

const handleResetForm = () => {
  form.value = {
    name: isNameDisabled.value ? form.value.name : '',
    leader: '',
    content: '',
    warningLevel: '',
    interventionLevel: '',
    isClosed: false,
    interventionTime: '',
  };
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

const handleExceed = () => {
  ElMessage.warning('只能上传一个文件');
};

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  const isAcceptedType = [
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/zip',
  ].includes(file.type);

  if (!isAcceptedType) {
    ElMessage.error('上传文件格式不正确!');
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
  }
  return isAcceptedType && isLt2M;
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.table-box {
  margin-bottom: 20px;
}
.dialog-footer {
  text-align: right;
}
</style>
